package eu.orangeflash.webapis.xmlrpc
{
	import flash.events.*;
	import flash.net.*;
	
	import eu.orangeflash.webapis.events.XMLRPCEvent;
	import eu.orangeflash.webapis.xmlrpc.utils.*;
	
	public class MethodCall
	extends EventDispatcher
	implements IMethodCall
	{
		protected var urlLoader:URLLoader = new URLLoader();
		protected var urlRequest:URLRequest = new URLRequest();
		
		protected var serviceClient:IClient;
		protected var name:String;
		protected var args:Array;
		protected var response:IMethodResponse;
		
		public function MethodCall(client:IClient)
		{
			this.client = client;
			configureHandlers();			
		}
		
		public function invoke(methodName:String = null, params:Array = null):void
		{
			methodName = (methodName == null)?this.methodName:methodName;
			params = (params == null)?this.params:params;
			
			urlRequest.data = Serialize.createMethod(methodName,params);
			urlLoader.load(urlRequest);
			
			dispatchEvent(new XMLRPCEvent(XMLRPCEvent.INVOKE, client, this));
		}
		
		[Bindable]
		public function set params(value:Array):void
		{
			args = value;
		}
		public function get	params():Array
		{
			return args;
		}	
		
		[Bindable]
		public function set methodName(value:String):void
		{
			name = value;
		}
		public function get methodName():String
		{
			return name;
		}
		
		[Bindable]
		public function set client(value:IClient):void
		{
			serviceClient = value;
			urlRequest.url = value.serviceURL;
			urlRequest.method = URLRequestMethod.POST;
			urlRequest.contentType = "text/xml";
		}
		public function get client():IClient
		{
			return serviceClient;
		}
		
		[Bindable(event="result")]
		public function get data():Object
		{
			return urlLoader.data;
		}
		
		[Bindable(event="result")]
		public function get result():IMethodResponse
		{
			return response;
		}
		
		protected function configureHandlers():void
		{
			urlLoader.addEventListener(Event.COMPLETE,onComplete);
		}
		
		private function onComplete(event:Event):void
		{
			response = Deserialize.createResponse(XML(urlLoader.data));
			if(response.isFault)
			{
				dispatchEvent(new XMLRPCEvent(XMLRPCEvent.FAULT, client, this));
			}else
			{
				dispatchEvent(new XMLRPCEvent(XMLRPCEvent.RESULT, client, this));
			}			
		}
	}
}